package com.transaction.simulate.controller;

import com.transaction.common.base.BaseController;
import com.transaction.common.base.User;
import com.transaction.common.util.JwtTokenUtil;
import com.transaction.common.util.ParamsUtil;
import com.transaction.simulate.model.dto.Role;
import com.transaction.simulate.model.vo.MenuVo;
import com.transaction.simulate.model.vo.RoleMenuVo;
import com.transaction.simulate.service.RoleService;
import com.transaction.simulate.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 用户
 * @author: dy.yin 2021/8/17 15:44
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    private static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 登录
     * @Title: login
     * @author: dy.yin 2021/8/17 16:04
     * @param: [accountNo, passWord, request]
     * @return: java.lang.Object
     * @throws
     */
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        String accountName = user.getAccountName();
        String passWord = user.getPassWord();
        if (StringUtils.isEmpty(accountName) || StringUtils.isEmpty(passWord)) {
            return "请输入用户名和密码！";
        }

        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                accountName,
                passWord
        );
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            LOGGER.info("用户名不存在！"+ e.getLocalizedMessage());
            throw new AuthenticationException("用户名不存在！");
        } catch (AuthenticationException e) {
            LOGGER.info("账号或密码错误！"+ e.getLocalizedMessage());
            throw new AuthenticationException("账号或密码错误！");
        } catch (AuthorizationException e) {
            LOGGER.info("没有权限！"+ e.getLocalizedMessage());
            throw new AuthenticationException("没有权限！");
        }

        user = userService.getUserByAccountName(accountName);
        user.setPassWord(null);
        String token = JwtTokenUtil.creatToken(user,JwtTokenUtil.SIMULATE_SECRET);
        Map<String,Object> data = new HashMap<>();
        data.put("token",token);
        data.put("user",user);
        data.put("project","/simulate");

        return retResultVo(data);
    }

    /**
     * 根据用户code查询菜单
     * @Title: getUserMenu
     * @author: dy.yin 2022/3/10 13:04
     * @param: [user]
     * @return: {@link Object }
     */
    @PostMapping("/getUserMenu")
    public Object getUserMenu(@RequestBody MenuVo menuVo){
        return retResultVo(userService.getUserMenu(menuVo));
    }


    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public Object addUser(@RequestBody @Valid User user){
        return retResultVo(userService.addUser(user));
    }


    /**
     * 查询角色列表
     * @return
     */
    @GetMapping("/getRoles")
    public Object getRoles(){
        return retResultVo(userService.getRoles());
    }

    //authorizationRole
    @GetMapping("/authorizationRole")
    public Object authorizationRole(HttpServletRequest request){
        Role role = ParamsUtil.getBeanParam(new Role(),request);
        if(role != null && StringUtils.isNotEmpty(role.getRoleCode())){
            return retResultVo(roleService.authorizationRole(role.getRoleCode()));
        }
        return retResultVo("请选择授权的角色");

    }

    //deleteRole
    @PostMapping("/deleteRole")
    public Object deleteRole(@RequestBody Role role){
        if(Objects.nonNull(role) && StringUtils.isNotEmpty(role.getRoleCode())){
            roleService.deleteRole(role.getRoleCode());
        }
        return retResultVo();
    }

    //addRole
    @PostMapping("/addRole")
    public Object addRole(@RequestBody Role role){
        roleService.addRole(role);
        return retResultVo();
    }

    //addRoleMenu
    @PostMapping("/addRoleMenu")
    public Object addRoleMenu(@RequestBody RoleMenuVo roleMenuVo){
        roleService.addRoleMenu(roleMenuVo);
        return retResultVo();
    }

}
